from Ft.Xml import Parse
import sqlite3, types

class Config:
	def __init__(self,filename):
		self.name 	= filename
		self.db		= Database()
		self.Parse()
	def Parse(self):
		doc = Parse(self.name)
		
		## Read Database Config
		self.db.type = doc.xpath('string(config//database//@type)') 
		self.db.version = doc.xpath('string(config//database//@version)') 
		
		if self.db.type == "SQLite":
			self.db.filename = doc.xpath('string(config//database//filename//@src)') 		
		if self.db.type == "MySQL":
			self.db.server 		= doc.xpath('string(config//database//server)') 
			self.db.username 	= doc.xpath('string(config//database//username)') 
			self.db.password 	= doc.xpath('string(config//database//password)') 

class Database:
	"""A base db, with commands"""
	## TODO: Create other SQL DB verions like MySQL and Firebird
	def __init__(self):
		self.type 		= None
		self.version 	= None
		self.filename 	= None
		self.server 	= None
		self.username 	= None
		self.password	= None
		self.port		= None
	
	def ParseConfig(self,config):
		self.type = config.db.type
		self.version = config.db.version
		if self.type == "SQLite":
			self.filename = config.db.filename
			
	def Connect(self):
		if self.type == "SQLite":
			self.conn = sqlite3.connect(self.filename)
			
	def Close(self):
		if self.type == "SQLite":
			self.cursor.close()
			del self
			
	def Query(self, q):
		if self.type == "SQLite":
			self.cursor = self.conn.cursor()
			self.cursor.execute(q)
			if q.find("UPDATE") > -1 or q.find("INSERT") > -1 or q.find("DELETE") > -1:
				self.conn.commit()
			
	def Fetch(self, all=True):
		if self.type == "SQLite":
			data = None
			fields = self.cursor.description
			if all: data = self.cursor.fetchall()
			else: data = self.cursor.fetchone()
			self.result = []
			
			if not all:
				row = {}
				if data:
					for i,field in enumerate(fields):
						row[field[0]] = data[i]
				else: row = None
				self.result.append(row)
			else:
				if data:
					for block in data:
						row = {}
						for i,field in enumerate(fields):
							row[field[0]] = block[i]
						self.result.append(row)






